//
//  UITableView+KLAutoTracker.m
//  RKLFoundationFrame
//
//  Created by RKL on 2018/3/6.
//  Copyright © 2018年 AppFrameWorkDemo. All rights reserved.
//

#import "UITableView+KLAutoTracker.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import "KLAutoTrackerOperation.h"
#import "NSObject+KLAutoTracker.h"

@implementation UITableView (KLAutoTracker)

+ (void) startTracker
{
    Method setDelegateMethod = class_getInstanceMethod(self, @selector(setDelegate:));
    Method KLSetDelegateMethod = class_getInstanceMethod(self, @selector(kl_setDelegate:));
    
    method_exchangeImplementations(setDelegateMethod, KLSetDelegateMethod);
}

- (void) kl_setDelegate:(id <UITableViewDelegate>)delegate
{
    //只监听UITableView
    if (![self isMemberOfClass:[UITableView class]])
    {
        return;
    }
    
    [self kl_setDelegate:delegate];
    
    if (delegate)
    {
        Class class = [delegate class];
        SEL originSelector = @selector(tableView:didSelectRowAtIndexPath:);
        SEL swizzlSelector = NSSelectorFromString(@"kl_didSelectRowAtIndexPath");
        BOOL didAddMethod = class_addMethod(class, swizzlSelector, (IMP)kl_didSelectRowAtIndexPath, "v@:@@");
        if (didAddMethod)
        {
            Method originMethod = class_getInstanceMethod(class, swizzlSelector);
            Method swizzlMethod = class_getInstanceMethod(class, originSelector);
            method_exchangeImplementations(originMethod, swizzlMethod);
        }
        
    }
    
}
void kl_didSelectRowAtIndexPath(id self, SEL _cmd, id tableView, NSIndexPath *indexpath)
{
    SEL selector = NSSelectorFromString(@"kl_didSelectRowAtIndexPath");
    ((void(*)(id, SEL,id, NSIndexPath *))objc_msgSend)(self, selector, tableView, indexpath);
    
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexpath];
    
    NSString * targetString = NSStringFromClass([self class]);
    NSString * actionString = NSStringFromSelector(_cmd);
    
    NSString * eventId = [NSString stringWithFormat:@"%@&&%@",targetString,actionString];
    NSDictionary * infoDictionary = [cell klInfoDictionary];
    
    [[KLAutoTrackerOperation sharedInstance] sendTrackerData:eventId
                                                        info:infoDictionary];
    
}
@end





















